package com.onegroup.pojo.dto;

import com.alibaba.fastjson2.annotation.JSONField;
import com.onegroup.pojo.Application;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: 曾雪斌
 * @Description: 登录后返回的账号信息
 * @History:
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ApplicationDto implements UserDetails, Serializable {

    private Application application;
    /**
     * 所拥有权限
     */
    List<String> permissions;

    /**
     * 授权信息
     * 不保存在redis
     */
    @JSONField(serialize = false)
    List<SimpleGrantedAuthority> authorities;

    public ApplicationDto(Application application, List<String> permissions) {
        this.application = application;
        this.permissions = permissions;
    }

    /**
     * 授权
     * @return 授权信息
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities != null) {
            return authorities;
        }

        authorities = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return authorities;
    }

    @Override
    public String getPassword() {
        return application.getAppPassword();
    }

    @Override
    public String getUsername() {
        return application.getAppUsername();
    }

    /**
     * 账号是否过期
     * @return true=账号没有过期 false = 账号过期
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 账号是否没被锁定
     * @return true=没被锁定 false=被锁定
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 证书是否没有过期
     * @return true=证书没有过期 false=证书过期
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 账号是否可用
     * @return true=可用 false=不可用
     */
    @Override
    public boolean isEnabled() {
        return true;
    }
}
